package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.constant.UserConstant;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.mapper.StoreMapper;
import com.graduation.springbootinit.model.entity.ShopPart.Store;
import com.graduation.springbootinit.model.entity.User;
import com.graduation.springbootinit.service.StoreService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {
    
    @Override
    public String getStoreNameById(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Store store = this.getById(id);
        if (store == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return store.getName();
    }

    @Override
    public Store getStoreById(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Store store = this.getById(id);
        if (store == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return store;
    }

    @Override
    public List<Store> getStoresByUserId(Long userId) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.list(queryWrapper);
    }

    @Override
    public Store verifyStoreOwnership(Long storeId, HttpServletRequest request) {
        // 1. 获取当前登录用户
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        User currentUser = (User) userObj;
        Long userId = currentUser.getId();

        // 2. 查询商铺信息
        Store store = this.getById(storeId);
        if (store == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "商铺不存在");
        }

        // 3. 验证商铺所有权
        if (!store.getUserId().equals(userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问该商铺");
        }

        return store;
    }
} 